package com.powernode.config;

import com.powernode.filter.TokenTranslationFilter;
import com.powernode.handle.AccessDeniedHandlerImpl;
import com.powernode.handle.AuthenticationEntryPointImpl;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

/**
 * @Author 梁卓
 * @Version 1.0
 * @ClassName ResourceServerConfig
 * @Description 资源服务器配置
 * @Date 2024/07/21 14:53
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class ResourceServerConfig extends WebSecurityConfigurerAdapter {

    @Resource
    private AuthenticationEntryPointImpl authenticationEntryPoint;
    @Resource
    private AccessDeniedHandlerImpl accessDeniedHandler;
    @Resource
    private TokenTranslationFilter tokenTranslationFilter;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .cors().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
                // 编写token解析过滤器，将token转换为用户信息存放到security容器中，放在认证过滤器之前（无需再登录）
                .addFilterBefore(tokenTranslationFilter, UsernamePasswordAuthenticationFilter.class)
                .exceptionHandling()
                // 处理没有携带token的请求
                .authenticationEntryPoint(authenticationEntryPoint)
                // 处理携带token, 但权限不足的请求
                .accessDeniedHandler(accessDeniedHandler)
            .and()
                .authorizeHttpRequests()
                .antMatchers().permitAll()
                // 除了放行的请求，都需进行身份认证
                .anyRequest().authenticated();
    }
}
